//index.js
const util = require("../../utils/util.js");

//获取应用实例
var app = getApp()
Page({
  data: {
    orderList: [],
    refreshLish: "false",
    // date: '2016-09-01',
    // time: '12:01',
    // 预约时间数组
    bookingTimeArray: [],
    taskStartBtnStr: "开始任务",
    // 任务类型：1待完成  2已完成
    taskState: "",
    linkUrl: ""
  },
  // 数据加载
  onLoad: function (options) {
    console.log('onLoad')
    this.$wuxToast = app.wux(this).$wuxToast;
    this.setData({
      refreshLish: "true",
      taskState: options.state
    });
    var title = "";
    if (options.state == 1) {
      title = "待完成任务列表";
      this.setData({
        linkUrl: '/api/task/list'
      });
      
    } if (options.state == 2) {
        title = "已完成任务列表";
        this.setData({
          linkUrl: '/api/task/list'
        });
    }
    wx.setNavigationBarTitle({
      title: title
    });

    var adminUserViewId = wx.getStorageSync('adminUserViewId');
    var token = wx.getStorageSync('token');
    app.globalData.adminUserViewId = adminUserViewId;
    app.globalData.token = token;
  },
  // 页面出现
  onShow: function () {
    if (app.globalData.adminUserViewId === undefined || app.globalData.token === undefined || app.globalData.adminUserViewId === "" || app.globalData.token === "") {
      wx.redirectTo({ url: '/pages/login/login' });
      console.log("未登录，调取登录页面");
    } else {
      console.log("已登录，请求数据");
      // 已登录，请求数据
      if (this.data.refreshLish == "true") {
        console.log("需要重新刷新数据~~~~");
        this.refreshNewData();
        this.setData({
          refreshLish: "false"
        });
      }
    }
    console.log("页面出现.");
  },
  // 下拉刷新页面
  onPullDownRefresh: function () {
    this.refreshNewData();
    wx.stopPullDownRefresh();
  },
  // 打电话
  callPhoneClick: function (e) {
    var phoneNum = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phoneNum
    });
  },
  // 进入详情页面
  orderTapClick: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var orderList = this.data.orderList;
    var currentOrder = orderList[index];
    var urlLink = currentOrder.taskType;
    var taskId = currentOrder.taskId;
    var taskTime = currentOrder.taskTime;
    var taskAddress = currentOrder.recvAddress;
    var taskStatus = currentOrder.taskStatus;
    var installFee = currentOrder.installFee;
    var current_userViewId = currentOrder.keyUserViewId;
    var local_adminUserViewId = wx.getStorageSync('adminUserViewId');

    // wx.navigateTo({
    //   url: '/pages/' + urlLink + '/' + urlLink + '?id=' + taskId + '&time=' + taskTime + '&address=' + taskAddress + '&taskStatus=' + taskStatus + '&installFee=' + installFee
    // });
    // return;

    // 判断是否是该任务负责人
    if (current_userViewId != local_adminUserViewId) {
      console.log("你不是此任务的负责人");
      that.$wuxToast.show({
        type: 'text',
        timer: 1500,
        color: '#fff',
        text: '你不是此任务的负责人',
        success: () => console.log('文本内容')
      })
    } else {
      // 判断是否选择预约时间，若未选择预约时间则提示“请选择预约时间”
      var detailTime = this.data.bookingTimeArray[index];
      if (detailTime == '--:--' || detailTime == '') {
        that.$wuxToast.show({
          type: 'text',
          timer: 1500,
          color: '#fff',
          text: '请选择预约时间',
          success: () => console.log('文本内容')
        })
        return;
      }
      // 判断是否已经开始任务
      var currentTaskStartBtnStr = currentOrder.taskStartBtnStr;
      // if (currentTaskStartBtnStr == '开始任务') {
      //   that.$wuxToast.show({
      //     type: 'text',
      //     timer: 1500,
      //     color: '#fff',
      //     text: '请先开始任务，再编辑任务',
      //     success: () => console.log('文本内容')
      //   })
      //   return;
      // }
      // 进入任务详情页面
      wx.navigateTo({
        url: '/pages/' + urlLink + '/' + urlLink + '?id=' + taskId + '&time=' + taskTime + '&address=' + taskAddress + '&taskStatus=' + taskStatus + '&installFee=' + installFee
      });
    }
  },
  //刷新数据
  refreshNewData: function () {
    util.showLoading();
    var that = this;
    var urlStr = this.data.linkUrl;
    util.request(urlStr, "", function (res) {
      console.log("data===" + res.data.code);
      util.hideToast();
      var msg = res.data.msg;
      if (res.data.code === 800 || res.data.code === 900) {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '账号未登录，请重新登录。',
          success: () => console.log('文本内容')
        })
        wx.redirectTo({ url: '/pages/login/login' });
      } else {
        var newList = res.data.data;
        console.log("newList===" + newList);
        var i = 0;

        // // 测试模拟数据
        // newList = [{ "taskStatusText": "等待勘测", "keyUserViewId": "1005", "source": "2", "recvPhone": "13478457663" }, { "taskStatusText": "等待维护", "keyUserViewId": "1005", "source": "3", "recvPhone": "13478457663" }, { "taskStatusText": "等待安装", "keyUserViewId": "1005", "source": "2", "recvPhone": "13478457663" }, { "taskStatusText": "等待滤网维护", "keyUserViewId": "1005", "source": "3", "recvPhone": "13478457663" }, { "taskStatusText": "等待准备物料", "keyUserViewId": "1005", "taskStatus": "32", "source": "1", "recvPhone": "13478457663" }, { "taskStatusText": "准备物料中", "keyUserViewId": "1005", "taskStatus": "33", "source": "1", "recvPhone": "13478457663" }];

        var local_adminUserViewId = wx.getStorageSync('adminUserViewId');

        if (newList != null) {
          newList.forEach(function (e) {
            var orderType = e.taskStatusText;
            if (orderType == "等待准备物料" || orderType == "准备物料中") {
              e.taskType = "task_material";
            } if (orderType == "等待勘测") {
              e.taskType = "task_houseSurvey";
            } if (orderType == "等待维护") {
              e.taskType = "task_equipmentMaintenance";
            } if (orderType == "等待安装") {
              e.taskType = "task_doorInstallation";
            } if (orderType == "等待滤网维护") {
              e.taskType = "task_filterMaintenance";
            }

            // 预约时间数组赋值
            var detailTime = e.detailTime;
            var bookTime;
            if (e.detailTime == "") {
              bookTime = ["--:--"];
            } else {
              bookTime = [detailTime];
            }
            var bookTimeArray = that.data.bookingTimeArray;
            bookTimeArray = bookTimeArray.concat(bookTime);
            that.setData({
              bookingTimeArray: bookTimeArray
            });
            // 判断是否是该任务负责人，用来判断是否展示操作按钮
            var current_userViewId = e.keyUserViewId;
            if (e.keyUserViewId === local_adminUserViewId) {
              e.showOperationBtns = 1;
            } else {
              e.showOperationBtns = 0;
            }
            // 判断该任务是否已经开始
            if (e.startTime != "") {
              e.taskStartBtnStr = "任务已开始";
            } else {
              e.taskStartBtnStr = "开始任务";
            }
            // 更换数据
            newList[i] = e;
            i++;
          });
          // 给数组赋值
          that.setData({
            orderList: newList
          });
        }
      }
    })
  },
  // 预约时间
  bindTimeChange: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var reserTimeStr = e.detail.value;
    var detailTime = this.data.orderList[index].detailTime;

    if (detailTime != "") {
      that.$wuxToast.show({
        type: 'text',
        timer: 1000,
        color: '#fff',
        text: '不可重复选择预约时间',
        success: () => console.log('提交成功')
      });
    } else {
      this.data.bookingTimeArray[index] = e.detail.value;
      var taskIdStr = this.data.orderList[index].taskId;
      //加载提示框
      util.showLoading();
      var urlString = app.globalData.BaseURL + '/api/task/updateReserTime';
      var dataSource = util.json2Form({
        taskId: taskIdStr,
        reserTime: reserTimeStr
      });
      // 请求后台预约时间
      wx.request({
        method: "POST",
        url: urlString,
        data: dataSource,
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
          'adminUserViewId': app.globalData.adminUserViewId,
          'token': app.globalData.token
        },
        success: function (res) {
          util.hideToast();
          var code = res.data.code;
          if (code === 200) {
            that.$wuxToast.show({
              type: 'text',
              timer: 1000,
              color: '#fff',
              text: '上传成功',
              success: () => console.log('提交成功')
            });
            that.refreshNewData();
          }
        }
      });
      console.log(index);
      this.setData({
        bookingTimeArray: this.data.bookingTimeArray
      })
    }
  },
  // 开始任务
  startTaskAction: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var currentOrder = this.data.orderList[index];
    var startTime = currentOrder.startTime;
    var urlLink = currentOrder.taskType;
    var taskId = currentOrder.taskId;
    var taskTime = currentOrder.taskTime;
    var taskAddress = currentOrder.recvAddress;
    var taskStatus = currentOrder.taskStatus;
    var installFee = currentOrder.installFee;

    // 判断是否选择预约时间，若未选择预约时间则提示“请选择预约时间”
    var detailTime = this.data.bookingTimeArray[index];
    if (detailTime == '--:--' || detailTime == '') {
      that.$wuxToast.show({
        type: 'text',
        timer: 1500,
        color: '#fff',
        text: '请先选择预约时间，再开始任务',
        success: () => console.log('文本内容')
      })
      return;
    }

    // 若有开始日期则该任务一开始，提示用户任务已开始
    if (startTime != "") {
      that.$wuxToast.show({
        type: 'text',
        timer: 1000,
        color: '#fff',
        text: '任务已开始',
        success: () => console.log('提交成功')
      });
    } else {

      wx.showModal({
        title: '提示',
        content: '是否确定开始任务？',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            // 加载提示框
            util.showLoading();

            var urlString = app.globalData.BaseURL + '/api/task/startTask';
            var dataSource = util.json2Form({
              taskId: taskId
            });
            // 请求后台开始任务
            wx.request({
              method: "POST",
              url: urlString,
              data: dataSource,
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
                'adminUserViewId': app.globalData.adminUserViewId,
                'token': app.globalData.token
              },
              success: function (res) {
                // 结束加载
                util.hideToast();

                var code = res.data.code;
                if (code === 200) {
                  that.$wuxToast.show({
                    type: 'text',
                    timer: 1000,
                    color: '#fff',
                    text: '任务已开始',
                    success: () => console.log('提交成功')
                  });
                  // 刷新页面
                  that.refreshNewData();
                  // 进入任务详情页面
                  wx.navigateTo({
                    url: '/pages/' + urlLink + '/' + urlLink + '?id=' + taskId + '&time=' + taskTime + '&address=' + taskAddress + '&taskStatus=' + taskStatus + '&installFee=' + installFee
                  });
                } else {
                  that.$wuxToast.show({
                    type: 'text',
                    timer: 1000,
                    color: '#fff',
                    text: '开始任务失败，请稍后再试。',
                    success: () => console.log('提交成功')
                  });
                }
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })

    }
  }
})
